//创建遮罩层
const oMask = document.createElement("div");
oMask.id = "mask";
oMask.style.height = "100%";
oMask.style.width = "100%";

const oAdd = document.createElement("div");
oAdd.id = "addweb";
oAdd.innerHTML = `<div class="addCon">
    <b>添加网站</b> 
    <span class="input-item">
        <b>名称</b>
        <input id="new-web-title" name="title"/>
    </span>
    <span class="input-item">
        <b>URL</b>
        <input  id="new-web-url" name="url"/>
    </span>
    <span class="button-item">
        <button class="button-add" onclick="addWebSite()">添加</button>
        <button class="button-cance" onclick="cancelAdd()">取消</button>
    </span>
</div>`;

const dbSite = document.createElement("div");
dbSite.id = "addweb";
dbSite.innerHTML = `<div class="dbSite">
    <b>数据库设置</b>
    <span class="input-item">
        <b>用户名</b>
        <input  id="new-web-user" name="user-name"/>
    </span>
    <span class="input-item">
        <b>Secret Key</b>
        <input id="new-web-title" name="secret-key"/>
    </span>
    <span class="input-item">
        <b>API Code</b>
        <input  id="new-web-url" name="api-code"/>
    </span>
    <span class="button-item">
        <button class="button-add" onclick="setDBInfo()">设 置</button>
        <button class="button-cance" onclick="cancelDBSite()">取 消</button>
    </span>
</div>`;


const webTable = 't_website_store'

let index = 0
// 增加网站
function addWebSite() {
    // 获取输入的标题和URL
    const titleInput = $('#new-web-title');
    const urlInput = $('#new-web-url');

    const title = titleInput[0].value;
    const url = urlInput[0].value;
    titleInput[0].value = ""
    urlInput[0].value = ""
    const logoURL = getWebsiteLogo(url)

    if (title !== "" && url !== "") {
        addWebsiteInfo(title, url, logoURL, index)
        index++
        // 存错记录
        holdWebsiteInfo(title, url, logoURL)
    }

    cancelAdd()
}

// 添加网站信息
function addWebsiteInfo(title, url, logoURL, key) {
    const container = $('#content-container');
    const webInfo = ` <div id="web-link-${key}" class="web-link">
        <span class="operate-back" id="operate-back-${key}">
            <span class="operate-button-${key} operate-button" onclick="clickMore('${key}')">
                <img id="option-icon" class="edit-icon edit-icon-${key}"
                     src="./img/more.png"/>
            </span>
        </span>

        <span class="web-img" onclick="gotoURL('${url}')">
            <img id="web-logo"
                 src="${logoURL}"
                 alt="web log"/>
        </span>
        <span class="web-title" onclick="gotoURL('${url}')">
            <p id="title-content">${title}</p>
        </span>
    </div>`
    // 向前添加元素
    container.prepend(webInfo)

    // 无法加载图片时加载默认图片
    $("#web-logo").one("error", function () {
        $(this).attr("src", "img/web.png");
    });

    $("#web-link-" + key).hover(() => {
        const editIcon = $(".edit-icon-" + key)
        if (editIcon[0].id === "") {
            editIcon[0].id = "option-icon"
        } else {
            editIcon[0].id = ""
        }
    })

    $(".operate-back-" + key).hover(() => {
        const operateButton = $(".operate-button-" + key)
        if (operateButton[0].id === "") {
            operateButton[0].id = "operate-button-hover"
        } else {
            operateButton[0].id = ""
        }
    })
}

// 存错记录
function holdWebsiteInfo(title, url, logoURL) {
    const UserName = window.localStorage.getItem("user_name")
    const query = Bmob.Query(webTable);
    query.set("web_title", encodeURI(title))
    query.set("web_url", url)
    query.set("web_logo_url", logoURL)
    query.set("user", UserName)
    query.save().catch(err => {
        console.log(err)
    })
}

// 显示添加网站编辑框
function dialog(mode) {
    //获取页面的高度和宽度
    const sWidth = document.body.scrollWidth || document.documentElement.scrollWidth;

    //获取页面的可视区域高度和宽度
    const wHeight = document.documentElement.clientHeight || document.body.clientHeight;

    //创建遮罩层
    document.body.appendChild(oMask);

    //创建添加对话框
    document.body.appendChild(mode);

    //获取编辑框的宽和高
    const dHeight = mode.offsetHeight;
    const dWidth = mode.offsetWidth;

    //设置编辑框的left和top
    mode.style.left = sWidth / 2 - dWidth / 2 + "px";
    mode.style.top = wHeight / 2 - dHeight / 2 + "px";

}

// 页面跳转
function gotoURL(url) {
    window.location.href = url
}

// 关闭添加网站编辑框
function cancelAdd() {
    document.body.removeChild(oAdd);
    document.body.removeChild(oMask);
}


// 关闭数据库编辑框
function cancelDBSite() {
    document.body.removeChild(dbSite);
    document.body.removeChild(oMask);
}


// 获取网站logo
function getWebsiteLogo(webURL) {
    const url = String(webURL)
    // 截取网站域名
    const webURLs = url.match(/[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/);
    const baseURL = webURLs[0]
    const logoURL = baseURL.match(/(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+\.?/);

    // 拼接logo地址
    const ret = 'http://www' + logoURL[0] + '/favicon.ico'
    return ret
}

// 加载网站
function loadingWebSite() {
    // 获取安全码和秘钥
    const SecretKey = window.localStorage.getItem("secret_key")
    const APIKey = window.localStorage.getItem("api_key")
    const UserName = window.localStorage.getItem("user_name")
    if (SecretKey === null || APIKey === null || UserName === null) {
        dialog(dbSite)
    } else {
        // 加载数据库
        Bmob.initialize(SecretKey, APIKey)

        // 加载数据
        const query = Bmob.Query(webTable);
        query.containedIn("user", [UserName]);
        query.find().then(resp => {
            if (resp.length > 0) {
                for (let item of resp) {
                    const title = decodeURI(item.web_title)
                    const url = item.web_url
                    const logoUrl = item.web_logo_url
                    const objectID = item.objectId
                    addWebsiteInfo(title, url, logoUrl, objectID)
                }
            }
        })
    }


}

// 设置数据库
function setDBInfo() {
    const secretKeyInput = $('#new-web-title');
    const apiCodeInput = $('#new-web-url');
    const userNameInput = $('#new-web-user');

    const secretKey = secretKeyInput[0].value;
    const apiCode = apiCodeInput[0].value;
    const userName = userNameInput[0].value;
    secretKeyInput[0].value = ""
    apiCodeInput[0].value = ""
    userNameInput[0].value = ""

    window.localStorage.setItem("secret_key", secretKey)
    window.localStorage.setItem("api_key", apiCode)
    window.localStorage.setItem("user_name", userName)

    cancelDBSite()
    loadingWebSite()
}

// 点击跟多选项
const webOption = document.createElement("div");

function clickMore(key) {
    webOption.id = "addweb";
    webOption.innerHTML = `<div class="web-option">
    <b>编辑收藏</b>
    <span class="option-item">
        <button class="option-button" onclick="deleteInfo('${key}')">删 除</button>
    </span>
    <span class="option-item">
        <button class="option-button" onclick="cancelMore()">取 消</button>
    </span>
</div>`;
    dialog(webOption)
}

// 删除收藏
function deleteInfo(key) {
    // 加载数据库
    initDB()
    // 删除数据库
    const query = Bmob.Query(webTable)
    query.containedIn("objectId", [key]);
    query.destroy(key).then(res => {
        window.console.log('res:', res)
    }).catch(err => {
        window.console.log('err:', err)
    })

    // 删除元素
    $('#web-link-' + key).remove();

    // 关闭菜单
    cancelMore()
}

// 取消跟多选项
function cancelMore() {
    document.body.removeChild(webOption);
    document.body.removeChild(oMask);
}

function initDB() {
    const SecretKey = window.localStorage.getItem("secret_key")
    const APIKey = window.localStorage.getItem("api_key")
    Bmob.initialize(SecretKey, APIKey)
}
